import {Component, OnDestroy, OnInit, TemplateRef, ViewChild, ViewEncapsulation} from '@angular/core';

import {FormGroup} from '@angular/forms';
import {FlatTreeControl} from '@angular/cdk/tree';
import {MatTreeFlatDataSource, MatTreeFlattener} from '@angular/material/tree';
import {MatDialog, MatDialogRef} from '@angular/material/dialog';

import {baseAnimations} from '@base/animations';
import {BaseConfirmDialogComponent} from '@base/components/confirm-dialog/confirm-dialog.component';

import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/internal/operators';

import {SettingPermitService} from './permit.service';
import { PermitFormDialogComponent } from './permit-form/permit-form.component';


interface PermitNode {
    id: number;
    icon: string;
    method: string;
    permission_name: string;
    module: string;
    parentId: number;
    route: string;
    type:number;
    children?: PermitNode[];
}

/** Flat node with expandable and level information */
interface PermitFlatNode {
    expandable: boolean;
    id: number;
    name: string;
    routing: string;
    method: string;
    type: number;
    level: number;
}

@Component({
    selector   : 'permissions-permit',
    templateUrl: './permit.component.html',
    styleUrls  : ['./permit.component.scss'],
    animations   : baseAnimations,
    encapsulation: ViewEncapsulation.None
})


export class PermitComponent implements OnInit, OnDestroy
{
    // Private
    private _unsubscribeAll: Subject<any>;

    @ViewChild('dialogContent', {static: false})
    dialogContent: TemplateRef<any>;
    dialogRef: any;
    confirmDialogRef: MatDialogRef<BaseConfirmDialogComponent>;

    treeControl: FlatTreeControl<PermitFlatNode>;
    treeFlattener: MatTreeFlattener<PermitNode, PermitFlatNode>;
    dataSource: MatTreeFlatDataSource<PermitNode, PermitFlatNode>;
    permit: any;

    public data: object[] = [];

    public permits: PermitNode[];

    /**
     * Constructor
     */
    constructor (
        private _settingPermitService: SettingPermitService,
        private _matDialog: MatDialog

    )
    {
        // Set the private defaults
        this._unsubscribeAll = new Subject();

        this.treeControl = new FlatTreeControl<PermitFlatNode>(
            node => node.level, node => node.expandable);

        this.treeFlattener = new MatTreeFlattener(
            ((node: PermitNode, level: number) => {
                return {
                    expandable: !!node.children && node.children.length > 0,
                    id: node.id,
                    name: node.permission_name,
                    routing: node.route,
                    method: node.method,
                    level: level,
                    type: node.type
                };
            }), node => node.level, node => node.expandable, node => node.children);

        this.dataSource = new MatTreeFlatDataSource(this.treeControl, this.treeFlattener);

        this._settingPermitService.onPermissionsChanged
            .pipe(takeUntil(this._unsubscribeAll))
            .subscribe(permits => {
                this.permits =  permits;
            });

        this.dataSource.data = this.permits;
        console.log(this.dataSource.data)

    }

    hasChild = (_: number, node: PermitFlatNode) => node.expandable;


    ngOnInit(): void
    {

    }

    /**
     * On destroy
     */
    ngOnDestroy(): void
    {
        // Unsubscribe from all subscriptions
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
    }

    // -----------------------------------------------------------------------------------------------------
    // @ Public methods
    // -----------------------------------------------------------------------------------------------------

    /**
     * New Permit
     */
    newPermit(): void
    {
        this.dialogRef = this._matDialog.open(PermitFormDialogComponent, {
            panelClass: 'permit-form-dialog',
            data      : {
                action: 'new'
            }
        });

        this.dialogRef.afterClosed()
            .subscribe((response: FormGroup) => {
                if ( !response )
                {
                    return;
                }

                this._settingPermitService.savePermit(response.getRawValue());
            });
    }

    /**
     * Edit Permit
     *
     * @param permit
     */
    editPermit(permit): void
    {
        console.log(permit);
        this.dialogRef = this._matDialog.open(PermitFormDialogComponent, {
            panelClass: 'permit-form-dialog',
            data      : {
                permit: permit,
                action : 'edit'
            }
        });

        this.dialogRef.afterClosed()
            .subscribe(response => {
                if ( !response )
                {
                    return;
                }
                const actionType: string = response[0];
                const formData: FormGroup = response[1];
                switch ( actionType )
                {
                    /**
                     * Save
                     */
                    case 'save':

                        this._settingPermitService.savePermit(formData.getRawValue());

                        break;
                    /**
                     * Delete
                     */
                    case 'delete':

                        this.deletePermit(permit);

                        break;
                }
            });
    }

    /**
     * Delete Permit
     */
    deletePermit(permit): void
    {
        this.confirmDialogRef = this._matDialog.open(BaseConfirmDialogComponent, {
            disableClose: false
        });

        this.confirmDialogRef.componentInstance.confirmMessage = 'Are you sure you want to delete?';

        this.confirmDialogRef.afterClosed().subscribe(result => {
            if ( result )
            {
                this._settingPermitService.deletePermit(permit);
            }
            this.confirmDialogRef = null;
        });

    }

}
